// src/main/updater.ts
import { autoUpdater, ProgressInfo } from 'electron-updater'
import {  dialog } from 'electron'
import { join } from 'path'
import { is } from '@electron-toolkit/utils' // 导入工具函数
import { WindowCreator } from '../hooks/createdWindow'

let downloadWindow: WindowCreator | null = null

export function setupAutoUpdate() {
  autoUpdater.autoDownload = false
  autoUpdater.autoInstallOnAppQuit = true

  // 创建下载进度窗口
  function createDownloadWindow() {
    let url = ''
     if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    url = `${process.env['ELECTRON_RENDERER_URL']}/update.html`
  } else {
    url = join(__dirname, '../../renderer/update.html')
  }

    downloadWindow = new WindowCreator({
      width: 400,
      height: 300,
      title: '主窗口',
      entry: url
    })
  }

  autoUpdater.on('update-available', (info) => {
    downloadWindow?.window?.webContents.send('update-available', info)

    dialog
      .showMessageBox({
        type: 'info',
        title: '发现新版本',
        message: `发现新版本 ${info.version}，是否现在下载？`,
        buttons: ['下载', '取消']
      })
      .then((result) => {
        if (result.response === 0) {
          createDownloadWindow()
          autoUpdater.downloadUpdate()

          // 主进程监听下载进度
          autoUpdater.on('download-progress', (progress: ProgressInfo) => {
            downloadWindow?.window?.webContents.send('download-progress', progress)
          })
        }
      })
  })

  autoUpdater.on('update-downloaded', () => {
    if (downloadWindow && downloadWindow.window && !downloadWindow.window.isDestroyed()) {
      downloadWindow.window.close()
    }

    dialog
      .showMessageBox({
        type: 'info',
        title: '更新准备就绪',
        message: '新版本已下载完成，是否立即安装？',
        buttons: ['立即安装', '稍后']
      })
      .then((result) => {
        if (result.response === 0) {
          autoUpdater.quitAndInstall()
        }
      })
  })

  autoUpdater.on('error', (error) => {
    console.error('更新错误:', error)
    downloadWindow?.window?.webContents.send('update-error', error)

    if (downloadWindow && downloadWindow.window && !downloadWindow.window.isDestroyed()) {
      downloadWindow.window.webContents.send('download-error', error)
    }
  })

  // 检查更新
  autoUpdater.checkForUpdatesAndNotify()
}
